import type { 
  ChatSessionVo, 
  ChatMessageDetailVo, 
  SaveRecordParams, 
  SaveRecordResponse,
  PageResult
} from '@/api/chat/types';
import { 
  getChatSessionPage, 
  getChatMessagePage, 
  saveRecord, 
  deleteChatSessions 
} from '@/api/chat';

/**
 * 报告聊天服务 - 处理会话记录和会话列表
 */
export class ReportChatService {
  private currentConversationId: number | null = null;

  /**
   * 设置当前会话ID
   */
  setConversationId(id: number | null) {
    this.currentConversationId = id;
  }

  /**
   * 获取当前会话ID
   */
  getConversationId(): number | null {
    return this.currentConversationId;
  }

  /**
   * 创建新会话
   */
  createNewConversation() {
    this.currentConversationId = null;
  }

  /**
   * 获取会话列表
   */
  async getChatSessions(params: {
    page?: number;
    limit?: number;
    orderField?: string;
    order?: string;
  } = {}): Promise<PageResult<ChatSessionVo>> {
    const defaultParams = {
      page: 1,
      limit: 100000,
      orderField: 'create_date',
      order: 'desc',
      ...params
    };
    
    const response = await getChatSessionPage(defaultParams);
    return response.result?.data || { list: [], total: 0 };
  }

  /**
   * 获取会话消息列表
   */
  async getChatMessages(sessionId: number, params: {
    page?: number;
    limit?: number;
    orderField?: string;
    order?: string;
  } = {}): Promise<PageResult<ChatMessageDetailVo>> {
    const defaultParams = {
      page: 1,
      limit: 100000,
      orderField: 'message_id',
      order: 'desc',
      sesssionId: sessionId,
      ...params
    };
    
    const response = await getChatMessagePage(defaultParams);
    return response.result?.data || { list: [], total: 0 };
  }

  /**
   * 保存会话记录
   */
  async saveConversationRecord(data: SaveRecordParams): Promise<SaveRecordResponse | null> {
    try {
      const response = await saveRecord(data);
      if (response.result?.code === 0) {
        return response.result.data;
      }
      throw new Error(response.result?.msg || '保存会话记录失败');
    } catch (error) {
      console.error('保存会话记录失败:', error);
      throw error;
    }
  }

  /**
   * 删除会话
   */
  async deleteSessions(ids: number[]): Promise<boolean> {
    try {
      const response = await deleteChatSessions(ids);
      return response.result?.code === 0;
    } catch (error) {
      console.error('删除会话失败:', error);
      return false;
    }
  }

  /**
   * 格式化会话列表为分组结构
   */
  formatSessionsToGroups(sessions: ChatSessionVo[]): Array<{ date: string; data: ChatSessionVo[] }> {
    const todayStart = new Date();
    todayStart.setHours(0, 0, 0, 0);
    
    const fiveDaysAgo = new Date(todayStart);
    fiveDaysAgo.setDate(fiveDaysAgo.getDate() - 5);
    
    const thirtyDaysAgo = new Date(todayStart);
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

    const dateGroups: Record<string, ChatSessionVo[]> = {};

    sessions.forEach((session) => {
      const sessionDate = new Date(session.createDate);
      
      if (sessionDate >= todayStart) {
        // 今天
        if (!dateGroups['今天']) dateGroups['今天'] = [];
        dateGroups['今天'].push(session);
      } else if (sessionDate >= fiveDaysAgo) {
        // 5天内
        if (!dateGroups['5天内']) dateGroups['5天内'] = [];
        dateGroups['5天内'].push(session);
      } else if (sessionDate >= thirtyDaysAgo) {
        // 30天内
        if (!dateGroups['30天内']) dateGroups['30天内'] = [];
        dateGroups['30天内'].push(session);
      } else {
        // 其他日期
        const dateStr = sessionDate.toLocaleDateString();
        if (!dateGroups[dateStr]) dateGroups[dateStr] = [];
        dateGroups[dateStr].push(session);
      }
    });

    return Object.keys(dateGroups).map(date => ({
      date,
      data: dateGroups[date]
    }));
  }
}

// 创建默认实例
export const reportChatService = new ReportChatService();
